/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.itxiaoq.imgConvert;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 *
 * @author xiaoqiang
 */
public class ImgConvert {

    private Image img;
    private int width;
    private int height;
    private String fileName;

    public ImgConvert(String filePath) throws IOException {
        File file = new File(filePath);
        fileName = file.getName();
        img = ImageIO.read(file);
        width = img.getWidth(null);
        height = img.getHeight(null);
    }

    public ImgConvert(File file) throws IOException {
//		File file = new File(filePath);

        fileName = file.getName();
        img = ImageIO.read(file);
        width = img.getWidth(null);
        height = img.getHeight(null);
    }

    /**      *
     * 强制压缩/放大图片到固定的大小      *
     * @param w int 新宽度      *
     * @param h int 新高度      *
     */
    public void resize(String outPath,Integer minifyNum) throws IOException {
        int bl = minifyNum;
        int w = width / bl;
        int h = height / bl;
        
//        w = 321;
//        h = 241;
        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢  

        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, w, h, null); // 绘制缩小后的图  

        image = ImgConvert.rotateImage(image, 90);
        String dirPath = outPath;
        File dirFile = new File(dirPath);

        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        File destFile = new File(dirPath + "/" + fileName);

        ImageIO.write(image, "jpg", destFile);

    }

    public static BufferedImage rotateImage(final BufferedImage bufferedimage, final int degree) {

        int w = bufferedimage.getWidth();
        int h = bufferedimage.getHeight();
        int type = bufferedimage.getColorModel().getTransparency();
        BufferedImage img;
        if (90 == degree || 270 == degree) {
            img = new BufferedImage(h, w, type);
        } else {
            img = new BufferedImage(w, h, type);
        }
        Graphics2D graphics2d;
        graphics2d = img.createGraphics();
        graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        if (270 == degree) {
            graphics2d.rotate(Math.toRadians(degree), w / 2, w / 2);
        } else if (90 == degree) {
            graphics2d.rotate(Math.toRadians(degree), h / 2, h / 2);
        }
        graphics2d.drawImage(bufferedimage, 0, 0, null);
        graphics2d.dispose();
        return img;
    }
}
